package com.slz.crm.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.slz.crm.common.exiception.BaseException;
import com.slz.crm.common.exiception.ServiceException;
import com.slz.crm.common.untils.*;
import com.slz.crm.pojo.ao.RoleAO;
import com.slz.crm.pojo.dto.UserDTO;
import com.slz.crm.pojo.entity.UserEntity;
import com.slz.crm.pojo.vo.UserVO;
import com.slz.crm.server.annotation.Privacy;
import com.slz.crm.server.constant.MessageConstant;
import com.slz.crm.server.mapper.UserMapper;
import com.slz.crm.server.properties.JwtProperties;
import com.slz.crm.server.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.*;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {


    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public String login(UserDTO userDTO) {

        userDTO.setPassword(DigestUtils.md5DigestAsHex(userDTO.getPassword().getBytes()));


        UserEntity user = userMapper.selectOne(new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getEmail, userDTO.getEmail())
                .eq(UserEntity::getPassword, userDTO.getPassword()));

        if(user == null || user.getId() == null){
            throw new BaseException(MessageConstant.PASS_OR_EMAIL_ERR);
        }

        Map<String, Object> map = new HashMap<>();

        RoleAO roleAO = new RoleAO();

        roleAO.setId(user.getId());
        roleAO.setRoleId(user.getRoleId());

        map.put("roleID",roleAO.getRoleId());
        map.put("userID",user.getId());

        return JwtUntil.createJWT(jwtProperties.getSecretKey(),jwtProperties.getTtl(),map);
    }

    @Override
    public String addUser(UserDTO userDTO) {


        if(userDTO.getRoleId() == null){
            throw new BaseException(MessageConstant.ROLE_IS_NOT_EXIST);
        }
        //TODO 管理员不能添加管理员
//        if(userDTO.getRoleId() == 1){
//            throw new BaseException(MessageConstant.MASTER_IS_ONE);
//        }
        //判断邮箱格式
        if(!ValidationUtils.isValidEmail(userDTO.getEmail())){
            throw new BaseException(MessageConstant.EMAIL_FORMAT_ERR);
        }
        //判断手机号格式
        if(!ValidationUtils.isValidMobile(userDTO.getPhone())){
            throw new BaseException(MessageConstant.IPHONE_IS_ERROR);
        }

        String password = "crm";
        //邮箱前四位
        password = password + userDTO.getEmail().substring(0,4);

                UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userDTO,userEntity);

        userEntity.setCreatorId(BaseUnit.getCurrentId());

        userEntity.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        userEntity.setStatus(0);
        userMapper.insert(userEntity);


        return password;
    }

    @Override
    public UserVO getById(Long userId) {

        UserEntity userEntity = userMapper.selectById(userId);

        if(userEntity == null){
            throw new BaseException(MessageConstant.USER_IS_NOT_EXIST);
        }

        return UserVO.fromEntity(userEntity);
    }

    @Override
    @Privacy
    public Page<UserVO> getAllUser(Integer pageNum, Integer pageSize) {
        Page<UserEntity> userEntityPage = new Page<>(pageNum,pageSize);
        Page<UserEntity> userEntityPage1 = userMapper.selectPage(userEntityPage, null);

        Page<UserVO> ans =new Page<>();
        BeanUtils.copyProperties(userEntityPage1,ans);

        List<UserVO> userVOS = new ArrayList<>();
        userEntityPage1.getRecords().forEach(userEntity -> {
            UserVO userVO = UserVO.fromEntity(userEntity);
            userVOS.add(userVO);
        });
        ans.setRecords(userVOS);

        return ans;
    }

    @Override
    public boolean updatePassword(String password) {
        Long currentId = BaseUnit.getCurrentId();
        UserEntity userEntity = new UserEntity();
        userEntity.setId(currentId);
        userEntity.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        int i = userMapper.updateById(userEntity);
        if(i == 0){
            throw new ServiceException(MessageConstant.UPDATE_ERR);
        }
        return true;
    }

    @Override
    public void updateUser(UserDTO userDTO) {
        userDTO.setPassword(null);
        Long currentId = BaseUnit.getCurrentId();
        UserEntity userEntity = userMapper.selectById(currentId);
        if(userEntity == null){
            throw new BaseException(MessageConstant.USER_IS_NOT_EXIST);
        }
        BeanUtils.copyProperties(userDTO,userEntity);
        userEntity.setId(currentId); // 修复 BeanUtils 覆盖导致 ID 丢失的问题
        int i = userMapper.updateById(userEntity);
        if(i == 0){
            throw new BaseException(MessageConstant.UPDATE_ERR);
        }
    }




}
